#include "addstudent.h"
#include "ui_addstudent.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>



addStudent::addStudent(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::addStudent)
{
    ui->setupUi(this);


    QNetworkAccessManager *manager=new QNetworkAccessManager(this);
    //处理响应结果
    connect(manager,&QNetworkAccessManager::finished,[this](QNetworkReply *reply){
        QString str = reply->readAll();
        qDebug()<<str;
        QJsonObject jsonObj =QJsonDocument::fromJson(str.toUtf8()).object();
        if (jsonObj.value("code").toInt() == 200)
        {
          QMessageBox::information(this, "成功", "添加新学员成功");

          this->close();
          // 当数据添加完成后，调用自定义信号，在主界面中来更新表格数据
          emit this->closeWIdgetFinished();
        }
        else
        {
          QMessageBox::critical(this, "失败", "添加新学员失败");
        }

    });

    //添加 发送请求
    connect(ui->pushButton,&QPushButton::clicked,[this,manager](){
        //收集数据
        QString name = ui->nameLineEdit->text();
        QString nickname = ui->nickLineEdit->text();
        QString gender = ui->comboBox->currentText();
        QString age = ui->ageLineEdit->text();
        QString dept = ui->deptLineEdit->text();
        qDebug()<<name<<nickname<<gender<<age<<dept;

        //发送请求
        // 设置请求头  固定格式
        QNetworkRequest request;
        request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
        // 设置请求的 Url地址
        request.setUrl(QUrl("http://127.0.0.1/school/api/v1.0/student"));
        //配置发送到服务端的数据
        QString params = QString("sname=%1&snickname=%2&sgender=%3&sage=%4&sdept=%5").arg(name)
                .arg(nickname).arg(gender).arg(age).arg(dept);
        // 发送 post请求  请求对象  发送到的数据
        manager->post(request,params.toUtf8());

    });



}

addStudent::~addStudent()
{
    delete ui;
}
